package edu.biwu.request;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

//处理多文件上传
@WebServlet("/req/upload02")
@MultipartConfig
public class ReqUploadDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.利用request对象中的getParts()方法获取所有的上传文件信息
        //每个上传文件的信息对应一个Part,然后将所有的Part存储到一个集合中
        Collection<Part> uploadFiles = request.getParts();

        //2.遍历所有的Part(所有的上传文件)
        //例如上传: 1.jpg 2.txt 3.pdf
        for (Part uploadFile : uploadFiles) {
            //1.通过Part接口的实现类对象获取上传文件的相关信息
        /*System.out.println(uploadFile.getSubmittedFileName());
        System.out.println(uploadFile.getContentType());
        System.out.println(uploadFile.getSize());*/
            String fileName = uploadFile.getSubmittedFileName();

            //2.保证存储文件名唯一，可以让用户重复上传文件
            String extension = fileName.substring(fileName.lastIndexOf("."));//截取文件的后缀名.jpg
            String newFileName = UUID.randomUUID() + extension;// 例如: asdfdf-123123-sdfasdf.jpg

            //3.规定将文件上传到D:/uploadFile文件夹下
            File file = new File("D:/uploadFile");
            if (!file.exists()) {//如果指定的上传路径在硬盘不存在,我们需要创建
                file.mkdirs();
            }

            //4.将上传的文件写入到指定的路径
            uploadFile.write(file + "/" + newFileName);
        }

        //5.上传成功后,响应上传成功提示
        String fileName = uploadFiles.stream().map((part -> part.getSubmittedFileName()))
                .collect(Collectors.joining(","));
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(fileName + "上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
